package com.hospital.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.hospital.model.PatientInfo;
import com.hospital.util.DbUtil;

public class PatientInfoDAO {
	
	public PatientInfo login(PatientInfo patient) {
		PatientInfo patientInfo = new PatientInfo();
		Connection conn = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		String sql = "select id, account, pswd, root, sex, birthday, address, tel, money from t_patient_info where account = ? and pswd = ? ";
		try {
			conn = DbUtil.getConnection();
			stmt = conn.prepareStatement(sql);
			stmt.setString(1, patient.getAccount());
			stmt.setString(2, patient.getPswd());
			rs = stmt.executeQuery();
			if (rs.next()) {
				patientInfo.setId(rs.getInt(1));
				patientInfo.setAccount(rs.getString(2));
				patientInfo.setPswd(rs.getString(3));
				patientInfo.setRoot(rs.getString(4));
				patientInfo.setSex(rs.getString(5));
				patientInfo.setBirthday(rs.getString(6));
				patientInfo.setAddress(rs.getString(7));
				patientInfo.setTel(rs.getString(8));
				patientInfo.setMoney(rs.getString(9));
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(rs);
			DbUtil.close(stmt);
			DbUtil.close(conn);
		}
		return patientInfo;
	}
	
	public boolean modifyPswd(PatientInfo patientInfo) {
		boolean flag = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		String sql = "update t_patient_info set pswd = ? where id = ?";
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, patientInfo.getPswd());
			pstmt.setInt(2, patientInfo.getId());
			int t = pstmt.executeUpdate();
			if (t >= 1) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(pstmt);
			DbUtil.close(conn);
		}
		return flag;
	}

	public boolean accountIsExist(String account) {
		boolean flag = false;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "select * from t_patient_info where account = ?";
		try {
			conn = DbUtil.getConnection();
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, account);
			rs = pstmt.executeQuery();
			while (rs.next()) {
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			DbUtil.close(rs);
			DbUtil.close(pstmt);
			DbUtil.close(conn);
		}
		return flag;
	}

}
